package com.tripwego.client.ui.widget;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.tripwego.client.event.ExpandCollapseEvent;
import com.tripwego.client.event.ExpandCollapseEventHandler;
import com.tripwego.client.event.UpdateEtapeEvent;
import com.tripwego.client.event.UpdateEtapeEventHandler;
import com.tripwego.client.model.DayModel;
import com.tripwego.client.model.EtapeModel;
import com.tripwego.client.ui.pageVoyage.IVoyageView;

public class EtapeContentWidget extends Composite implements IVoyageView, UpdateEtapeEventHandler, ExpandCollapseEventHandler {

	private Presenter presenter;

	private EventBus eventBus;

	private EtapeModel etapeModel = null;

	/*
	 * Elements graphiques
	 */
	private VerticalPanel panel_listDay = new VerticalPanel();

	/**
	 * 
	 */
	public EtapeContentWidget() {
		super();

		panel_listDay.setStyleName("EtapeContentWidget");

		initWidget(panel_listDay);
	}

	public void deleteActivite(int index) {
		panel_listDay.remove(index);
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;

		// ecouteurs d'evenements
		eventBus.addHandler(UpdateEtapeEvent.TYPE, this);
		eventBus.addHandler(ExpandCollapseEvent.TYPE, this);
	}

	@Override
	public void init() {
		panel_listDay.clear();

		for (DayModel dayModel : etapeModel.getListDay()) {

			DayWidget dayWidget = new DayWidget();
			dayWidget.setPresenter(presenter);
			dayWidget.setEventBus(eventBus);
			dayWidget.setDayModel(dayModel);
			dayWidget.init();

			panel_listDay.add(dayWidget);
		}
	}

	/**
	 * @return the etapeModel
	 */
	public EtapeModel getEtapeModel() {
		return etapeModel;
	}

	/**
	 * @param etapeModel
	 *            the etapeModel to set
	 */
	public void setEtapeModel(EtapeModel etapeModel) {
		this.etapeModel = etapeModel;
	}

	@Override
	public void handleUpdateEtapeEvent(UpdateEtapeEvent event) {
		EtapeModel etapeModelUpdate = event.getEtapeModel();

		if (etapeModelUpdate.getId().equals(etapeModel.getId())) {
			setEtapeModel(etapeModelUpdate);
			init();
		}
	}

	@Override
	public void handleExpandCollapseEvent(ExpandCollapseEvent event) {

		boolean expand = event.isExpand();

		for (int i = 0; i < panel_listDay.getWidgetCount(); i++) {
			DayWidget dayWidget = (DayWidget) panel_listDay.getWidget(i);
			dayWidget.open(expand);
		}
	}
}
